package com.ruoyi.interview.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.interview.domain.InterviewQuestion;
import com.ruoyi.interview.domain.InterviewAnswer;
import com.ruoyi.interview.service.IInterviewAnswerService;
import com.ruoyi.interview.service.IInterviewQuestionService;
import com.ruoyi.interview.service.IInterviewReportGenerateService;
import com.ruoyi.interview.service.IInterviewReportService;
import com.ruoyi.interview.service.IInterviewDimensionScoreService;
import com.ruoyi.interview.service.IInterviewDimensionService;
import com.ruoyi.interview.domain.InterviewReport;
import com.ruoyi.interview.domain.InterviewDimensionScore;
import com.ruoyi.interview.domain.InterviewDimension;
import com.ruoyi.web.util.ChatUtil;
import com.ruoyi.interview.domain.vo.DeepSeekQuestionVO;
import com.ruoyi.interview.domain.vo.DeepSeekResponseData;
import com.ruoyi.interview.mapper.InterviewQuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.interview.mapper.InterviewRecordMapper;
import com.ruoyi.interview.domain.InterviewRecord;
import com.ruoyi.interview.service.IInterviewRecordService;

/**
 * 模拟面试记录Service业务层处理
 * 
 * @author lishugen
 * @date 2025-06-12
 */
@Service
public class InterviewRecordServiceImpl implements IInterviewRecordService 
{
    @Autowired
    private InterviewRecordMapper interviewRecordMapper;

    @Autowired
    private InterviewQuestionMapper interviewQuestionMapper;

    @Autowired
    private IInterviewQuestionService interviewQuestionService;

    @Autowired
    private IInterviewAnswerService interviewAnswerService;

    @Autowired
    private IInterviewReportService interviewReportService;

    @Autowired
    private IInterviewDimensionScoreService interviewDimensionScoreService;

    @Autowired
    private IInterviewDimensionService interviewDimensionService;

    /**
     * 查询模拟面试记录
     * 
     * @param id 模拟面试记录主键
     * @return 模拟面试记录
     */
    @Override
    public InterviewRecord selectInterviewRecordById(Long id)
    {
        return interviewRecordMapper.selectInterviewRecordById(id);
    }

    /**
     * 查询模拟面试记录列表
     * 
     * @param interviewRecord 模拟面试记录
     * @return 模拟面试记录
     */
    @Override
    public List<InterviewRecord> selectInterviewRecordList(InterviewRecord interviewRecord)
    {
        return interviewRecordMapper.selectInterviewRecordList(interviewRecord);
    }

    /**
     * 新增模拟面试记录
     * 
     * @param interviewRecord 模拟面试记录
     * @return 结果
     */
    @Override
    public int insertInterviewRecord(InterviewRecord interviewRecord)
    {
        interviewRecord.setCreateTime(DateUtils.getNowDate());
        return interviewRecordMapper.insertInterviewRecord(interviewRecord);
    }

    /**
     * 修改模拟面试记录
     * 
     * @param interviewRecord 模拟面试记录
     * @return 结果
     */
    @Override
    public int updateInterviewRecord(InterviewRecord interviewRecord)
    {
        interviewRecord.setUpdateTime(DateUtils.getNowDate());
        return interviewRecordMapper.updateInterviewRecord(interviewRecord);
    }

    /**
     * 批量删除模拟面试记录
     * 
     * @param ids 需要删除的模拟面试记录主键
     * @return 结果
     */
    @Override
    public int deleteInterviewRecordByIds(Long[] ids)
    {
        return interviewRecordMapper.deleteInterviewRecordByIds(ids);
    }

    /**
     * 删除模拟面试记录信息
     * 
     * @param id 模拟面试记录主键
     * @return 结果
     */
    @Override
    public int deleteInterviewRecordById(Long id)
    {
        return interviewRecordMapper.deleteInterviewRecordById(id);
    }

    @Override
    public Long gennerateRecord(Long positionId, String message) {

        //1.添加面试记录，拿到新添加面试记录的ID
        //1.1获取到当前登录微信的用户ID
        Long wxUserID= SecurityUtils.getLoginUser().getUserId();
        //1.2创建并存储面试记录
        InterviewRecord record = new InterviewRecord();
        record.setUserId(wxUserID);
        record.setPositionId(positionId);
        //新增面试记录
        interviewRecordMapper.insertInterviewRecord(record);
        //2.添加问题
        DeepSeekResponseData data = JSONObject.parseObject(message, DeepSeekResponseData.class);
        //得到问题
        List<DeepSeekQuestionVO> questions = data.getQuestions();
        //创建一个面试问题的数组
        List<InterviewQuestion> interviewQuestions=new ArrayList<>();
        for (int i = 0; i < questions.size(); i++) {
            //取到里面的每一个对象
            DeepSeekQuestionVO question = questions.get(i);
            //创建一个InterviewQuestion对象
            InterviewQuestion interviewQuestion = new InterviewQuestion();
            //把循环出来的值添加到这interviewQuestion对象里面去
            interviewQuestion.setRecordId(record.getId());
            interviewQuestion.setQuestionNo((long) i);
            interviewQuestion.setContent(question.getText());
            interviewQuestion.setCreateTime(new Date());
            interviewQuestion.setQuestionPrompt(question.getSample_answer());
            //把对象添加到集合中去
            interviewQuestions.add(interviewQuestion);

        }
        //编写批量插入的接口
        interviewQuestionMapper.insertInterviewQuestionBacth(interviewQuestions);
        //3.返回面试记录的ID
        return record.getId();
    }

    @Override
    public List<InterviewQuestion> start(Long recodeId) {
        //1.修改面试记录状态
        InterviewRecord record = interviewRecordMapper.selectInterviewRecordById(recodeId);
        //添加开始时间
        record.setStartTime(new Date());
        //设置状态 0：开始
        record.setStatus("0");
        //修改表里面的数据
        interviewRecordMapper.updateInterviewRecord(record);

        //2.查询面试题目
        InterviewQuestion query = new InterviewQuestion();
        query.setRecordId(record.getId());
        List<InterviewQuestion> interviewQuestions = interviewQuestionMapper.selectInterviewQuestionList(query);
        return interviewQuestions;
    }

    @Override
    public String finish(Long recodeId) {
        // 1. 更新面试记录结束时间与状态
        InterviewRecord record = interviewRecordMapper.selectInterviewRecordById(recodeId);
        record.setEndTime(new Date());
        if (record.getStartTime() != null) {
            long durationSec = (record.getEndTime().getTime() - record.getStartTime().getTime()) / 1000;
            record.setDuration(durationSec);
        }
        record.setStatus("1");
        interviewRecordMapper.updateInterviewRecord(record);

        // 2. 查询该岗位的维度信息
        List<InterviewDimension> dimensions = interviewDimensionService.selectDimensionByPostionId(record.getPositionId());
        
        // 3. 查询该记录的所有问题与答案
        InterviewQuestion query = new InterviewQuestion();
        query.setRecordId(record.getId());
        List<InterviewQuestion> questions = interviewQuestionService.selectInterviewQuestionList(query);

        StringBuilder qa = new StringBuilder();
        
        // 3.1 添加维度信息到提示词中
        if (dimensions != null && !dimensions.isEmpty()) {
            qa.append("### 评估维度配置\n");
            for (InterviewDimension dim : dimensions) {
                qa.append("维度ID: ").append(dim.getId())
                  .append(", 维度名称: ").append(dim.getName())
                  .append(", 权重: ").append(dim.getWeight());
                if (dim.getDescription() != null && !dim.getDescription().isEmpty()) {
                    qa.append(", 描述: ").append(dim.getDescription());
                }
                qa.append("\n");
            }
            qa.append("\n");
        }
        
        // 3.2 添加问题与答案
        qa.append("### 面试问题与回答\n");
        for (int i = 0; i < questions.size(); i++) {
            InterviewQuestion q = questions.get(i);
            InterviewAnswer ansQuery = new InterviewAnswer();
            ansQuery.setQuestionId(q.getId());
            List<InterviewAnswer> answers = interviewAnswerService.selectInterviewAnswerList(ansQuery);
            String answerText = answers != null && !answers.isEmpty() && answers.get(0).getContent() != null
                    ? answers.get(0).getContent() : "";
            qa.append("问题").append(i + 1).append("：").append(q.getContent()).append("\n");
            qa.append("回答").append(i + 1).append("：").append(answerText).append("\n\n");
        }

        // 4. 调用AI生成报告（严格JSON）
        IInterviewReportGenerateService aiService = ChatUtil.getService(IInterviewReportGenerateService.class);
        String reportJson = aiService.generateReport(qa.toString());
        // 5. 保存报告（基础字段）
        try {
            com.alibaba.fastjson2.JSONObject obj = com.alibaba.fastjson2.JSONObject.parseObject(reportJson);
            InterviewReport report = new InterviewReport();
            report.setRecordId(record.getId());
            if (obj.get("overall_score") != null) {
                java.math.BigDecimal score = new java.math.BigDecimal(String.valueOf(obj.get("overall_score")));
                report.setOverallScore(score);
            }
            report.setOverallEvaluation(obj.getString("overall_evaluation"));
            report.setStrengths(obj.getString("strengths"));
            report.setWeaknesses(obj.getString("weaknesses"));
            report.setSuggestions(obj.getString("suggestions"));
            report.setGenerateTime(new Date());
            interviewReportService.insertInterviewReport(report);
            
            // 6. 保存维度评分信息
            com.alibaba.fastjson2.JSONArray dimensionScores = obj.getJSONArray("dimension_scores");
            if (dimensionScores != null && !dimensionScores.isEmpty()) {
                for (int i = 0; i < dimensionScores.size(); i++) {
                    com.alibaba.fastjson2.JSONObject dimObj = dimensionScores.getJSONObject(i);
                    InterviewDimensionScore dimensionScore = new InterviewDimensionScore();
                    dimensionScore.setReportId(report.getId());
                    
                    // 设置维度ID
                    if (dimObj.get("dimension_id") != null) {
                        dimensionScore.setDimensionId(Long.valueOf(String.valueOf(dimObj.get("dimension_id"))));
                    }
                    
                    // 设置维度得分
                    if (dimObj.get("score") != null) {
                        java.math.BigDecimal dimScore = new java.math.BigDecimal(String.valueOf(dimObj.get("score")));
                        dimensionScore.setScore(dimScore);
                    }
                    
                    // 设置维度评价
                    dimensionScore.setEvaluation(dimObj.getString("evaluation"));
                    dimensionScore.setCreateTime(new Date());
                    
                    // 保存到数据库
                    interviewDimensionScoreService.insertInterviewDimensionScore(dimensionScore);
                }
            }
        } catch (Exception ignore) { }

        return reportJson;
    }
}
